<template>
    <div id="login">
        <div class="form_wrap">
            <ul class="menu_tab">
                <li
                    v-for="(item, index) in data.tab_menu"
                    :key="index"
                    :class="{'current' : data.current_menu === item.type }"
                    @click="clickToggleMenu(item.type)"
                >{{ item.label }}</li>
            </ul>
            <el-form ref="form_account" :model="data.form" :rules="data.rules">
                <el-form-item prop="username">
                    <label class="form_label">邮箱</label>
                    <el-input v-model="data.form.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <label class="form_label">密码</label>
                    <el-input v-model="data.form.password" type="password"></el-input>
                </el-form-item>
                <el-form-item v-show="data.current_menu === 'register'" prop="passwords">
                    <label class="form_label">确认密码</label>
                    <el-input v-model="data.form.passwords" type="password"></el-input>
                </el-form-item>
                <el-form-item prop="code">
                    <label class="form_label">验证码</label>
                    <div class="div_code">
                        <el-input v-model="data.form.code" class="code_input"></el-input>
                        <el-button
                            class="code_button"
                            type="success"
                            @click="clickGetCode"
                            :loading="data.code_button_loading"
                            :disabled="data.code_button_disabled"
                        >{{ data.code_button_text }}</el-button>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button
                        class="submit_button"
                        type="danger"
                        :loading="data.submit_button_loading"
                        :disabled="data.submit_button_disabled"
                        @click="clickSubmitForm"
                    >{{ data.current_menu === "login" ? "登录" : "注册" }}</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import { reactive, getCurrentInstance, onBeforeUnmount } from "vue"
import { validate_username, validate_password, validate_code, checkPassword } from "@/utils/validate.js"
import { getCodeApi, errorHttpApi } from "@/api/common.js"
import { registerApi, loginApi, accountCheckApi } from "@/api/account.js"
import sha1 from "js-sha1"
import { useRouter } from "vue-router"

export default {
    name: 'Login',
    setup(props) {
        const { proxy } = getCurrentInstance()
        const router = useRouter()
        const validate_username_rules = (rule, value, callback) => {
            if(!value || value === ""){
                callback( new Error("请输入邮箱") )
                return
            }else if(!validate_username(value)){
                callback( new Error("请格式正确的邮箱") )
                return
            }else{
                callback()
            }
        }
        const validate_password_rules = (rule, value, callback) => {
            if(!value || value === ""){
                callback( new Error("请输入密码") )
                return
            }else if(!validate_password(value)){
                callback( new Error("请输入>=6并且<=20位的密码，包含数字、字母") )
                return
            }else{
                callback()
            }
        }
        const validate_passwords_rules = (rule, value, callback) => {
            if( !value || value === "" ){
                callback( new Error("请再次输入密码") )
                return
            }else if(value !== data.form.password){
                callback( new Error("请确保再次输入的密码跟上面保持一致") )
                return
            }else{
                callback()
            }
        }
        const validate_code_rules = (rule, value, callback) => {
            if( !value || value === "" ){
                callback( new Error("请输入验证码") )
                return
            }
            if( !validate_code(value) ){
                callback( new Error("请有效的6位数验证码") )
                return
            }else{
                callback()
            }
        }
        const data = reactive({
            tab_menu: [
                { type: "login", label: "登录" },
                { type: "register", label: "注册" },
            ],
            current_menu: "login",
            code_button_disabled: false,   //启用按钮
            code_button_loading: false,    //加载状态
            code_button_text: "获取验证码", //按钮文本
            code_button_timer: null,       //定时器对象
            form_account: null,
            form: {
                username: "",
                password: "",
                passwords: "",
                code: null
            },
            rules: {
                username: [
                    { validator: validate_username_rules, trigger: "change" }
                ],
                password: [
                    { validator: validate_password_rules, trigger: "change" }
                ],
                passwords: [
                    { validator: validate_passwords_rules, trigger: "change" }
                ],
                code: [
                    { validator: validate_code_rules, trigger: "change" }
                ],
            },
            submit_button_disabled: true,   //启用按钮
            submit_button_loading: false,    //加载状态
        })
        
        // tab点击事件
        const clickToggleMenu = (type) => {
            data.current_menu = type
        }

        // 验证码点击事件
        const clickGetCode = () => {
            const username = data.form.username;
            const password = data.form.password;
            const passwords = data.form.passwords;
            let requestData = {}
            if(username === ""){
                proxy.$message({
                    message: "请输入邮箱",
                    type: "error"
                })
                return false
            }else if(!validate_username(username)){
                proxy.$message({
                    message: "请格式正确的邮箱",
                    type: "error"
                })
                return false
            }

            if(password === ""){
                proxy.$message({
                    message: "请输入密码",
                    type: "error"
                })
                return false
            }else if(!validate_password(password)){
                proxy.$message({
                    message: "请输入>=6并且<=20位的密码，包含数字、字母",
                    type: "error"
                })
                return false
            }

            if(data.current_menu === "login"){
                requestData = {
                    "username": username,
                    "module": "login"
                }
            }else if(data.current_menu === "register"){
                if(passwords === ""){
                    proxy.$message({
                        message: "请再次输入密码",
                        type: "error"
                    })
                    return false
                }else if(passwords !== password){
                    proxy.$message({
                        message: "请确保再次输入的密码跟上面保持一致",
                        type: "error"
                    })
                    return false
                }
                requestData = {
                    "username": username,
                    "module": "register"
                }
            }

            data.code_button_loading = true
            data.code_button_text = "发送中"

            // 响应错误测试接口
            // errorHttpApi(requestData).then(response => {
            //     console.log(response);
            // }).catch(error => {
            //     console.log(error);
            // })


            // 获取验证码接口
            getCodeApi(requestData).then(response => {
                if(response.resCode === 0){
                    proxy.$message({
                        message: `获取成功,验证码为：${response.data}`,
                        type: "success"
                    })
                    data.submit_button_disabled = false
                    countDown()
                }else if(data.current_menu === "register" && response.resCode === 1024){
                    proxy.$message({
                        message: "此邮箱用户名已经存在，请直接登录！",
                        type: "error",
                        duration: 2000,
                        onClose: () => {
                            data.current_menu = "login"
                            if(data.code_button_timer) { clearInterval(data.code_button_timer) }
                            data.code_button_text = "获取验证码"
                            data.code_button_loading = false
                            data.submit_button_disabled = true
                        }
                    })
                }else if(data.current_menu === "login" && response.resCode === 1024){
                    proxy.$message({
                        message: "此邮箱用户名不存在，请先注册！",
                        type: "error",
                        duration: 2000,
                        onClose: () => {
                            data.current_menu = "register"
                            if(data.code_button_timer) { clearInterval(data.code_button_timer) }
                            data.code_button_text = "获取验证码"
                            data.code_button_loading = false
                        }
                    })
                }
            }).catch(error => {
                data.code_button_loading = false
                data.code_button_text = "获取验证码"
            })
        }

        // 验证码60秒倒计时
        const countDown = (time) => {
            let thetime = time || 60
            data.code_button_loading = false
            data.code_button_disabled = true
            data.code_button_text = `倒计时${thetime}秒`
            if(data.code_button_timer) { clearInterval(data.code_button_timer) }
            data.code_button_timer = setInterval(() => {
                thetime--
                data.code_button_text = `倒计时${thetime}秒`
                if(thetime <= 0){
                    data.code_button_disabled = false
                    data.code_button_text = "再次获取"
                    clearInterval(data.code_button_timer)
                }
            }, 1000)
        }

        const clickSubmitForm = () => {
            if(data.form.passwords === ""){
                data.form.passwords = data.form.password
            }
            proxy.$refs.form_account.validate(valid => {
                if(valid){
                    data.current_menu === "login" ? login() : register()
                }
            })
        }
        const register = () => {
            data.submit_button_loading = true
            const registerData = {
                username: data.form.username,
                password: sha1(data.form.password),
                code: data.form.code,
            }

            registerApi(registerData).then(response => {
                proxy.$message({
                    message: "注册成功，请登录！",
                    type: "success",
                    duration: 2000,
                    onClose: () => {
                        form_reset()
                    }
                })
            }).catch(error => {
                data.submit_button_loading = false
                proxy.$message({
                    // 验证码输入错误或者网络问题
                    message: "验证码错误或网络出错，请重新注册！",
                    type: "error",
                    duration: 2000
                })
            })


        }
        const login = () => {
            const loginData = {
                username: data.form.username,
                password: sha1(data.form.password),
                code: data.form.code,
            }
            data.submit_button_loading = true
            loginApi(loginData).then(response => {
                proxy.$message({
                    message: "登录成功",
                    type: "success",
                    duration: 2000,
                    onClose: () => {
                        // 登录成功后，跳转后台首页
                        router.push({ path: "/home" })
                    }
                })
            }).catch(error => {
                data.submit_button_loading = false
                proxy.$message({
                    message: "密码错误或网络出错，请重新登录！",
                    type: "error",
                })
            })




        }

        const form_reset = () => {
            data.current_menu = "login"
            data.code_button_timer && clearInterval(data.code_button_timer) //清除定时器
            data.submit_button_loading = false //提交按钮停止加载
        }

        // 销毁组件之前 清除定时器
        onBeforeUnmount(() => {
            clearInterval(data.code_button_timer)
        })

        return { data, clickToggleMenu, clickGetCode, clickSubmitForm, router }
    }

};
</script>

<style lang="scss" scoped>
#login{
    height: 100vh;
    background-color: #344a5f;
    .form_wrap{
        width: 320px;
        padding-top: 100px;
        margin: auto;
        .menu_tab{
            text-align: center;
            margin-bottom: 40px;
            li{
                display: inline-block;
                padding: 10px 24px;
                margin: 0 10px;
                color: #fff;
                font-size: 14px;
                border-radius: 5px;
                cursor: pointer;
                &.current{
                    background-color: rgba(0, 0, 0, 0.1);
                }
            }
        }

        .form_label{
            display: block;
            color: #fff;
            font-size: 14px;
            margin-bottom: 5px;
        }
        .div_code{
            display: flex;
            justify-content:space-between;
            align-items: center;
            width: 100%;
            .code_input{
                width: 60%;
            }
            .codebutton{
                width: 30%;
                min-width: 100px;
                color: #fff;
            }

        }
        .submit_button{
            display: block;
            width: 100%;
            margin-top: 50px;
        }
    }
}
</style>